package com.company.bookstore.security;

import com.company.bookstore.entities.user_admin_module.User;
import com.company.bookstore.service.user_admin_module.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * UsernamePasswordProvider
 *
 * @blame Android Team
 */
@Component
@Slf4j
public class UsernamePasswordProvider implements AuthenticationProvider {
/**
 * 　　1. 如果同时指定了name和type，则从Spring上下文中找到唯一匹配的bean进行装配，找不到则抛出异常
 * 　　2. 如果指定了name，则从上下文中查找名称（id）匹配的bean进行装配，找不到则抛出异常
 * 　　3. 如果指定了type，则从上下文中找到类型匹配的唯一bean进行装配，找不到或者找到多个，都会抛出异常
 * 　　4. 如果既没有指定name，又没有指定type，则自动按照byName方式进行装配；如果没有匹配，则回退为一个原始类型进行匹配，如果匹配则自动装配；
 * */
    @Resource
    private UserService userDetailsService;

    @Resource
    BCryptPasswordEncoder passwordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单输入中返回的用户名
        String username = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();

        User user =  (User)userDetailsService.loadUserByUsername(username);

        if (null == user){
            log.info("没有该账号");
            throw new UsernameNotFoundException("没有该账号");
        }
        if (!passwordEncoder.matches(password,user.getPassword())){
            log.info("没有该账号");
            throw new BadCredentialsException("密码错误");
        }
        if (user.getEnable() == 0){
            log.info("该账号已经被冻结");
            throw new BadCredentialsException("账号已经被禁用");
        }
        if (user.getDeleted() == 1){
            log.info("该账号已被回收");
            throw new BadCredentialsException("该账号已被回收");
        }

        return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());

    }

    @Override
    public boolean supports(Class<?> authentication) {
       return authentication.equals(UsernamePasswordToken.class);
    }
}
